package com.doge.walknovel.business.home.library

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.setPadding
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelInfo
import com.doge.walknovel.api.model.process
import com.doge.walknovel.business.home.profile.topup.TopUpActivity
import com.doge.walknovel.business.home.profile.topup.TopUpRefer
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.business.search.SearchActivity
import com.doge.walknovel.core.BaseFragment
import com.doge.walknovel.core.base.Event
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.walknovel.core.base.postEvent
import com.doge.wnpro.databinding.FragmentLibraryBinding
import com.doge.walknovel.utils.setOnClickCallback
import com.doge.walknovel.utils.systemWindowInsetsTop
import com.doge.walknovel.widgets.AlertDialog

class LibraryFragment : BaseFragment() {
    private var innerBinding: FragmentLibraryBinding? = null
    private val binding get() = innerBinding!!
    private val viewModel: LibraryViewModel by activityViewModels()
    private val adapter by lazy { LibraryAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: FragmentLibraryBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        systemWindowInsetsTop.observe(viewLifecycleOwner) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            LibraryRepository.get().requestMyLib()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 3)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        initialViews()

        viewModel.loading.observe(viewLifecycleOwner) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(viewLifecycleOwner) {
            adapter.set(it)
            binding.layEmpty.visibility = if (it?.isNotEmpty() == true) View.GONE else View.VISIBLE
        }

        LibraryRepository.get().requestMyLib()
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> (item as? NovelInfo?).process(context, NovelRefer.library)
            BOOK_EDIT -> LibraryRepository.get().updateEditMode(true)
            BOOK_DEL -> displayDeleteDialog(item as? NovelInfo?)
            BOOK_ADD -> {
                LibraryRepository.get().updateEditMode(false)
                postEvent(Event.SWITCH_MAIN_TAB, 1)
            }
        }
    }

    private fun displayDeleteDialog(bookInfo: NovelInfo?) {
        if (bookInfo == null) return
        val context = context ?: return
        AlertDialog.Builder(context)
            .setMessage(getString(R.string.delete_this_book_or_not))
            .setNegativeButton(getString(R.string.cancel1)) { _, _ -> }
            .setPositiveButton(getString(R.string.delete)) { _, _ ->
                LibraryRepository.get().requestDeleteNovel(bookInfo)
            }
            .create().show()
    }

    private fun initialViews() {
        binding.edit.setOnClickCallback { LibraryRepository.get().updateSwitchEditMode() }
        binding.search.setOnClickCallback { SearchActivity.start(it.context) }
        binding.topUp.setOnClickCallback { TopUpActivity.start(it.context, TopUpRefer.library) }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        adapter.setListener(null)
        binding.recyclerView.adapter = null
        binding.edit.setOnClickListener(null)
        binding.search.setOnClickListener(null)
        binding.topUp.setOnClickListener(null)
        innerBinding = null
    }
}